package io.github.shenbinglife.springboot2.layui.config;

import io.github.shenbinglife.springboot2.layui.admin.controller.LoginController;
import io.github.shenbinglife.springboot2.layui.common.model.Result;
import io.github.shenbinglife.springboot2.layui.common.utils.ResponseUtils;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(LoginController.LOGIN_USER);
        if (attribute == null) {
            String contentType = request.getHeader("Accept");
            List<MimeType> mimeTypes = MimeTypeUtils.parseMimeTypes(contentType);
            if (mimeTypes.contains(MimeTypeUtils.APPLICATION_JSON)) {
                ResponseUtils.writeObjectAsJson(response, Result.failure("用户未认证"));
            } else {
                response.sendRedirect("/view/login");
            }
            return false;
        } else {
            return true;
        }
    }

}
